import email, sys, time
import email.Errors
import mailbox
import networkx as NX

def msgfactory(fp):
    try:
        return email.message_from_file(fp)
    except email.Errors.MessageParseError:
        return ''

cdef starG(mess,G):
    try:
        core
        core = mess.get('from').split()[-1].strip('<>')
        tips = []
        for j in mess.get_all('to')[0].split(','):
            tips.append(j.split()[-1].strip('<>'))
        ebunch = []
        for k in tips:
            ebunch.append((core,k))
        G.add_edges_from(ebunch)
        #print 'feito'
        return G
    except:
        print'falhou'
sta = time.clock()
cdef char *dir
dir='/home/flavio/Mail/inbox'#sys.argv[0]
mbox = mailbox.Maildir(dir, msgfactory) # mailbox do kmail
#fp = open('/home/flavio/.thunderbird/uwnuhl1p.default/Mail/malaria.procc.fiocruz.br/Inbox','r')
#mbox = mailbox.PortableUnixMailbox(fp,msgfactory)#mailbox do thunderbird
G = NX.Graph()
cdef int n
for n from 0<= n<1000:
    i = mbox.next()
    starG(i,G)
#fp.close()
print G.nodes()
print 'tempo:', time.clock()-sta

    
